using B.S.XZYData.Api.Wrter.Application.Command.Process;
using B.S.XZYData.Domain.ZSHH;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using System.Linq;

namespace B.S.XZYData.Api.Wrter.Application.Handler.Process
{
    /// <summary>
    /// 批量删除工序处理器
    /// </summary>
    public class BatchDeleteProcessHandler : IRequestHandler<BatchDeleteProcessCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<Domain.ZSHH.Process> processRepo;
        private readonly IBaseRepository<ProcessCollectionData> collectionDataRepo;
        private readonly ILogger<BatchDeleteProcessHandler> logger;

        public BatchDeleteProcessHandler(
            IBaseRepository<Domain.ZSHH.Process> processRepo,
            IBaseRepository<ProcessCollectionData> collectionDataRepo,
            ILogger<BatchDeleteProcessHandler> logger)
        {
            this.processRepo = processRepo;
            this.collectionDataRepo = collectionDataRepo;
            this.logger = logger;
        }

        /// <summary>
        /// 批量删除工序
        /// </summary>
        /// <param name="request">命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>返回统一包装类</returns>
        public async Task<ApiResult<int>> Handle(BatchDeleteProcessCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiResult<int>();

            try
            {
                if (request.Ids == null || !request.Ids.Any())
                {
                    res.Msg = "请选择要删除的工序";
                    res.Code = ApiEnum.Fail;
                    return await System.Threading.Tasks.Task.FromResult(res);
                }

                var totalResult = 0;

                foreach (var id in request.Ids)
                {
                    try
                    {
                        // 检查工序是否存在
                        var existingProcess = await processRepo.GetValue(id);
                        if (existingProcess == null || existingProcess.IsDeleted)
                        {
                            continue;
                        }

                        // 逻辑删除工序
                        existingProcess.IsDeleted = true;
                        existingProcess.Updator = request.Deleter;
                        existingProcess.UpdatorDate = DateTime.Now;

                        var processResult = await processRepo.UpdateAsync(existingProcess);
                        if (processResult > 0)
                        {
                            totalResult += processResult;

                            // 逻辑删除相关的工序采集数据
                            var collectionDataList = collectionDataRepo.GetAll()
                                .Where(x => !x.IsDeleted && x.ProcessId == id)
                                .ToList();

                            foreach (var item in collectionDataList)
                            {
                                item.IsDeleted = true;
                                item.Updator = request.Deleter;
                                item.UpdatorDate = DateTime.Now;
                                await collectionDataRepo.UpdateAsync(item);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        logger.LogError($"批量删除工序时，工序ID {id} 处理异常：{ex.Message}");
                        // 继续处理下一个，不中断整个批量操作
                    }
                }

                if (totalResult > 0)
                {
                    res.Data = totalResult;
                    res.Msg = $"批量删除工序成功，共删除 {totalResult} 条记录";
                    res.Code = ApiEnum.Success;
                }
                else
                {
                    res.Msg = "没有成功删除任何工序";
                    res.Code = ApiEnum.Fail;
                }

                logger.LogInformation($"批量删除工序完成，请求删除 {request.Ids.Count} 个，成功删除 {totalResult} 个");

                return await System.Threading.Tasks.Task.FromResult(res);
            }
            catch (Exception ex)
            {
                logger.LogError($"批量删除工序异常：{ex.Message}");
                res.Msg = "批量删除工序异常：" + ex.Message;
                res.Code = ApiEnum.Error;
                return await System.Threading.Tasks.Task.FromResult(res);
            }
        }
    }
} 